package mvc;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class DispatcherServlet extends HttpServlet {

    @Override
    public void init(ServletConfig config) throws ServletException {
        //获取类信息配置文件路径
        String path = config.getInitParameter("contentConfig");
        //将配置信息保存为输入流
        InputStream is = DispatcherServlet.class.getClassLoader().getResourceAsStream(path);
        HandlerMapping.load(is);
    }



    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取用户请求的url  xx.do
        String url = req.getRequestURI();
        HandlerMapping.MVCMapping mapping = HandlerMapping.get(url);
        if (mapping == null){
            //获取请求地址为空时，发送404错误给客户端
            resp.sendError(404,"MVC映射地址:"+url+"不存在");
            return;
        }

        Object obj = mapping.getObj();
        Method method = mapping.getMethod();
        Object result = null;

        try {
            //注解反射机制调用方法
            result = method.invoke(obj,req,resp);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            System.out.println("此处接收被调用方法内部未被捕获的异常");
            Throwable t = e.getTargetException(); //获取目标异常
            t.printStackTrace();
        }

        switch (mapping.getType()){
            //使用枚举类
            case TEXT:
                //向页面写数据
                resp.getWriter().write((String) result);
                break;
            case VIEW:
                //将页面重定向
                resp.sendRedirect((String) result);
                break;

        }

    }
}
